package com.demo.meidianapp.mvp.base.retroft;

import android.net.ParseException;
import android.util.Log;

import com.demo.meidianapp.utils.HttpException;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/*
 * 描述:     TODO 异常抛出帮助类
 */
public class ExceptionHelper {

    public static HttpException handleException(Throwable e) {
        e.printStackTrace();
        HttpException httpException = new HttpException();
        String error;
        int errorCode;
        if (e instanceof SocketTimeoutException) {//网络超时
            Log.e("TAG", "网络连接异常: SocketTimeoutException");
            error = e.getMessage();
            errorCode = 1000;
        } else if (e instanceof ConnectException) { //均视为网络错误
            Log.e("TAG", "网络连接异常: " + e.getMessage());
            error = e.getMessage();
            errorCode = 1000;
        } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof
                ParseException) {   //均视为解析错误
            Log.e("TAG", "数据解析异常: " + e.getMessage());
            error = e.getMessage();
            errorCode = 1001;
        } else if (e instanceof ApiException) {//服务器返回的错误信息
            error = e.getCause().getMessage();
            errorCode = 1002;
        } else if (e instanceof UnknownHostException) {
            Log.e("TAG", "网络连接异常: " + e.getMessage());
            error = e.getMessage();
            errorCode = 1000;
        } else if (e instanceof IllegalArgumentException) {
            Log.e("TAG", "下载文件已存在: " + e.getMessage());
            error = e.getMessage();
            errorCode = 1003;
        } else {//未知错误
            error = e.getMessage();
            try {
                Log.e("TAG", "错误: " + e.getMessage());
            } catch (Exception e1) {

                Log.e("TAG", "未知错误Debug调试 ");
            }
            errorCode = 1004;
        }
        httpException.setErrorCode(errorCode);
        httpException.setErrorMessage(error);
        return httpException;
    }

}